package com.blockchain.securewallet.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.UIHelper;

import static com.blockchain.securewallet.utils.ToolUtils.lastPointJudge;

public class UniversalDialog extends DialogFragment implements View.OnClickListener {

    private EditText mEditText;
    private EditText mEditText2;
    private EditText mEditText3;

    private TextView tvContent1;
    private TextView tvContent2;

    private TextView tvCancel;
    private TextView tvOk;
    private String okText;
    private String content;
    private boolean isOnly;

    //可存BTC/ETH的交易手续费
    private String customText;
    private String customLimit;
    private String customNonce;

    private int type = 0;

    public static final int TYPE_SINGLE_INPUT = 1;

    public static final int TYPE_BTC_FEE = 2;

    public static final int TYPE_ETH_FEE = 3;
    public static final int TYPE_LTC_FEE = 9;
    public static final int TYPE_BCH_FEE = 10;

    public static final int TYPE_RECEIVE = 4;

    //可输入的可见文本框(如设置收款金额，目前默认输入类型是数字)
    public static final int TYPE_INPUT_TEXT = 5;

    //文本框提示，内容只有一种类型
    public static final int TYPE_TIPS_SINGLE = 6;

    //文本框提示，内容有两种字体类型
    public static final int TYPE_TIPS_DOUBLE = 7;

    //混合提示（编辑框+文本框等）
    public static final int TYPE_TIPS_MIX = 8;

    private static boolean isNeedAdjust = false;

    private IDialogListener listener;
    private IDialogTipsListener tipsListener;


    public void setType(int type) {
        this.type = type;
    }

    public UniversalDialog() {
        // Empty constructor is required for DialogFragment
        // Make sure not to add arguments to the constructor
        // Use `newInstance` instead as shown below
    }

    public void setDialogListener(IDialogListener listener) {
        this.listener = listener;
    }

    public void setDialogListener(IDialogTipsListener listener2) {
        this.tipsListener = listener2;
    }

    public static UniversalDialog newInstance(String title) {
        UniversalDialog frag = new UniversalDialog();
        Bundle args = new Bundle();
        args.putString("title", title);
        frag.setArguments(args);
        return frag;
    }


    public static UniversalDialog showInputTextDialog(FragmentManager fm, IDialogListener listener, String title) {
        UniversalDialog dialog = UniversalDialog.newInstance(title);
        dialog.setType(UniversalDialog.TYPE_INPUT_TEXT);
        dialog.setDialogListener(listener);
        dialog.show(fm, "TYPE_INPUT_TEXT");
        return dialog;
    }

    public static UniversalDialog showSingeleTipDialog(FragmentManager fm, IDialogListener listener, String title, String content) {
        isNeedAdjust = true;
        UniversalDialog dialog = UniversalDialog.newInstance(title);
        dialog.setType(UniversalDialog.TYPE_TIPS_SINGLE);
        dialog.content = content;
        dialog.setDialogListener(listener);
        dialog.show(fm, "TYPE_TIPS_SINGLE");
        return dialog;
    }

    public static UniversalDialog showDoubleTipsDialog(FragmentManager fm, IDialogListener listener, String title, String okText, boolean isOnly) {
        isNeedAdjust = true;
        UniversalDialog dialog = UniversalDialog.newInstance(title);
        dialog.setType(UniversalDialog.TYPE_TIPS_DOUBLE);
        dialog.okText = okText;
        dialog.isOnly = isOnly;
        dialog.setDialogListener(listener);
        dialog.show(fm, "TYPE_TIPS_DOUBLE");
        return dialog;
    }

    public static UniversalDialog showMixDialog(FragmentManager fm, IDialogListener listener, String title) {
        UniversalDialog dialog = UniversalDialog.newInstance(title);
        dialog.setType(UniversalDialog.TYPE_TIPS_MIX);
        dialog.setDialogListener(listener);
        dialog.show(fm, "TYPE_TIPS_MIX");
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();

        if (!isNeedAdjust) return;

        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.88), ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        isNeedAdjust = false;
    }

    public static UniversalDialog showDialog(FragmentManager fm, IDialogTipsListener listener2) {
        isNeedAdjust = true;
        UniversalDialog dialog = UniversalDialog.newInstance("请输入支付密码");
        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");

        return dialog;
    }

    public static UniversalDialog showPayDialog(FragmentManager fm, IDialogTipsListener listener2) {
        isNeedAdjust = true;
        UniversalDialog dialog = UniversalDialog.newInstance("请输入支付密码");
        dialog.setType(UniversalDialog.TYPE_SINGLE_INPUT);
        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }

    public static UniversalDialog showBtcFeeDialog(FragmentManager fm, IDialogTipsListener listener2, String customText) {
        UniversalDialog dialog = UniversalDialog.newInstance(StringUtil.getResourceString(R.string.tips_set_fee));
        dialog.setType(UniversalDialog.TYPE_BTC_FEE);
        dialog.customText = customText;
        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }

    public static UniversalDialog showLtcFeeDialog(FragmentManager fm, IDialogTipsListener listener2, String customText) {
        UniversalDialog dialog = UniversalDialog.newInstance(StringUtil.getResourceString(R.string.tips_set_fee));
        dialog.setType(UniversalDialog.TYPE_LTC_FEE);
        dialog.customText = customText;
        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }

    public static UniversalDialog showBchFeeDialog(FragmentManager fm, IDialogTipsListener listener2, String customText) {
        UniversalDialog dialog = UniversalDialog.newInstance(StringUtil.getResourceString(R.string.tips_set_fee));
        dialog.setType(UniversalDialog.TYPE_BCH_FEE);
        dialog.customText = customText;
        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }


    /**
     * 显示ETH的手续费设置窗口，输入框带已存值
     *
     * @param fm        FragmentManager 使用DialogFragment必传的参数
     * @param listener2 用于监听包含View的事件
     * @param texts     视具体场景而定，ETH传3个，则顺序是Price、Limit、Nonce
     * @return
     */
    public static UniversalDialog showEthFeeDialog(FragmentManager fm, IDialogTipsListener listener2, String... texts) {
        UniversalDialog dialog = UniversalDialog.newInstance(StringUtil.getResourceString(R.string.tips_set_fee));
        dialog.setType(UniversalDialog.TYPE_ETH_FEE);

        switch (texts.length) {
            case 3:
                dialog.customNonce = texts[2];
            case 2:
                dialog.customLimit = texts[1];
            case 1:
                dialog.customText = texts[0];
                break;
        }

        dialog.setDialogListener(listener2);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }

    public static UniversalDialog showSetReceiveDialog(FragmentManager fm, IDialogListener listener) {
        UniversalDialog dialog = UniversalDialog.newInstance("接收金额");
        dialog.setType(UniversalDialog.TYPE_RECEIVE);
        dialog.setDialogListener(listener);
        dialog.show(fm, "fragment_edit_name");
        return dialog;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (type == TYPE_BTC_FEE || type == TYPE_ETH_FEE || type == TYPE_LTC_FEE || type == TYPE_BCH_FEE) {
            return inflater.inflate(R.layout.fee_set_dialog, container);
        }

        if (type == TYPE_INPUT_TEXT) return inflater.inflate(R.layout.dialog_input_text, container);
        if (type == TYPE_TIPS_SINGLE)
            return inflater.inflate(R.layout.dialog_tips_single, container);
        if (type == TYPE_TIPS_DOUBLE)
            return inflater.inflate(R.layout.dialog_tips_double, container);
        if (type == TYPE_TIPS_MIX) return inflater.inflate(R.layout.dialog_tips_mix, container);

        //默认是密码输入框
        return inflater.inflate(R.layout.dialog_input_password, container);
    }

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //这里的view是不为null
        tvCancel = view.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(this);
        tvOk = view.findViewById(R.id.tv_ok);
        //tvOk.setOnClickListener(this);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //默认为空字符而不为null是为了避免被调用String方法
                String text = "";
                if (mEditText != null) {
                    text = mEditText.getText().toString();
                }

                switch (type) {
                    case TYPE_SINGLE_INPUT:
                        if (lastPointJudge(text)) return;

                        if (listener != null) {
                            listener.onItemClick(text);
                        }

                        if (tipsListener != null) {
                            tipsListener.onItemClick(view, text);
                        }

                        if (!TextUtils.isEmpty(text) && text.equals(WalletApp.getInstance().getPayPassword())) {
                            dismiss();
                        }
                        break;
                    case TYPE_LTC_FEE:
                    case TYPE_BCH_FEE:
                    case TYPE_BTC_FEE:
                        if (lastPointJudge(text)) return;

                        if (listener != null) {
                            listener.onItemClick(text);
                        }

                        if (tipsListener != null) {
                            tipsListener.onItemClick(view, text);
                        }

                        if (!TextUtils.isEmpty(text)) {
                            dismiss();
                        }
                        break;
                    case TYPE_ETH_FEE:
                        if (lastPointJudge(text)) return;

                        if (listener != null) {
                            listener.onItemClick(text, mEditText2.getText().toString(), mEditText3.getText().toString());
                        }

                        if (tipsListener != null) {
                            tipsListener.onItemClick(view, text, mEditText2.getText().toString(), mEditText3.getText().toString());
                        }

                        if (!TextUtils.isEmpty(text)) {
                            dismiss();
                        }
                        break;
                    case TYPE_RECEIVE:
                        if (lastPointJudge(text)) return;

                        if (listener != null) {
                            listener.onItemClick(text);
                        }
                        dismiss();
                        break;
                    case TYPE_INPUT_TEXT:
                        if (listener != null) {
                            listener.onItemClick(text);
                        }
                        dismiss();
                        break;
                    case TYPE_TIPS_SINGLE:
                        if (listener != null) {
                            listener.onItemClick(tvContent1.getText().toString());
                        }
                        dismiss();
                        break;
                    case TYPE_TIPS_DOUBLE:
                        if (listener != null) {
                            listener.onItemClick(tvContent1.getText().toString(), tvContent2.getText().toString());
                        }
                        dismiss();
                        break;
                    case TYPE_TIPS_MIX:
                        if (lastPointJudge(text)) return;

                        if (listener != null) {
                            listener.onItemClick(text);
                        }
                        dismiss();
                        break;
                    default:
                        if (lastPointJudge(text)) return;

                        //默认是0
                        if (listener != null) {
                            listener.onItemClick(text, mEditText2.getText().toString());
                        }
                        if (tipsListener != null) {
                            tipsListener.onItemClick(view, text, mEditText2.getText().toString());
                        }
                        if (!TextUtils.isEmpty(text) && text.equals(mEditText2.getText().toString())) {
                            dismiss();
                        }
                        break;
                }
            }
        });


        // 根据布局类型对控件进行一些初始化
        switch (type) {
            case TYPE_BTC_FEE:
            case TYPE_LTC_FEE:
            case TYPE_BCH_FEE:
            case TYPE_ETH_FEE:
                initTradeInfo(view);
                break;
            case TYPE_INPUT_TEXT:
                mEditText = view.findViewById(R.id.et_input);
                break;
            case TYPE_TIPS_SINGLE:
                tvContent1 = view.findViewById(R.id.tv_content_fitst);

                if (StringUtil.isEmpty(content)) return;

                tvContent1.setText(content);
                break;
            case TYPE_TIPS_DOUBLE:
                tvContent1 = view.findViewById(R.id.tv_content_fitst);
                tvContent2 = view.findViewById(R.id.tv_content_second);
                View v_view_ver = view.findViewById(R.id.v_view_ver);

                if (isOnly) {
                    v_view_ver.setVisibility(View.GONE);
                    tvCancel.setVisibility(View.GONE);

                    ViewGroup.LayoutParams params = tvOk.getLayoutParams();
                    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                if (StringUtil.isEmpty(okText)) return;
                tvOk.setText(okText);
                break;
            case TYPE_TIPS_MIX:
                mEditText = view.findViewById(R.id.et_input);
                break;
            default:
                initSingleInput(view);
                break;
        }


        // Fetch arguments from bundle and set title
        String title = getArguments().getString("title", "Enter Name");
        getDialog().setTitle(title);
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
        tvTitle.setText(title);

        // Show soft keyboard automatically and request focus to field
        if (mEditText == null) return;
        mEditText.requestFocus();

        getDialog().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }

    private void initSingleInput(View view) {
        mEditText = (EditText) view.findViewById(R.id.edit_first_password);
        mEditText2 = (EditText) view.findViewById(R.id.edit_second_password);
        if (type == TYPE_SINGLE_INPUT || type == TYPE_RECEIVE) {
            mEditText2.setVisibility(View.GONE);
            if (type == TYPE_RECEIVE) {
                mEditText.setHint("请输入接收金额");
                mEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_TEXT);
            }
            
            TextView tv_tips_friendly = view.findViewById(R.id.tv_tips_friendly);
            TextView tv_tips_content = view.findViewById(R.id.tv_tips_content);
            tv_tips_friendly.setVisibility(View.GONE);
            tv_tips_content.setVisibility(View.GONE);
        }
    }

    private void initTradeInfo(View view) {
        mEditText = (EditText) view.findViewById(R.id.edit_fee);
        mEditText2 = (EditText) view.findViewById(R.id.edit_gaslimit);
        mEditText3 = (EditText) view.findViewById(R.id.edit_nonce);
        if (type==TYPE_ETH_FEE){
            mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }
        TextView tvUnit = (TextView) view.findViewById(R.id.tv_unit);
        TextView tvLabel = view.findViewById(R.id.tv_label);
        RelativeLayout rlSecond = view.findViewById(R.id.second_edit_zone);
        RelativeLayout rlThird = view.findViewById(R.id.third_edit_zone);

        //如果存在先前设定过的值，则显示
        if (StringUtil.noEmpty(customText)) {
            mEditText.setText(customText);
        }

        if (type == TYPE_BTC_FEE) {
            tvLabel.setVisibility(View.GONE);
            rlSecond.setVisibility(View.GONE);
            rlThird.setVisibility(View.GONE);
            tvUnit.setText("BTC/KB");

            ViewGroup.LayoutParams layoutParams = mEditText.getLayoutParams();
            layoutParams.width = UIHelper.dipToPx(160f);

        } else if (type == TYPE_LTC_FEE) {
            tvLabel.setVisibility(View.GONE);
            rlSecond.setVisibility(View.GONE);
            rlThird.setVisibility(View.GONE);
            tvUnit.setText("LTC/KB");

            ViewGroup.LayoutParams layoutParams = mEditText.getLayoutParams();
            layoutParams.width = UIHelper.dipToPx(160f);
        } else if (type == TYPE_BCH_FEE) {
            tvLabel.setVisibility(View.GONE);
            rlSecond.setVisibility(View.GONE);
            rlThird.setVisibility(View.GONE);
            tvUnit.setText("BCH/KB");

            ViewGroup.LayoutParams layoutParams = mEditText.getLayoutParams();
            layoutParams.width = UIHelper.dipToPx(160f);
        } else {
            tvLabel.setText("Gas:");
            tvUnit.setText("Gwei");

            //库神设定的Price/Limit默认值是 30/200,000 ,Nonce则没有
            if (StringUtil.noEmpty(customLimit)) {
                mEditText2.setText(customLimit);
            }
            if (StringUtil.noEmpty(customNonce)) {
                mEditText3.setText(customNonce);
            }

            tvLabel.setVisibility(View.VISIBLE);
            rlSecond.setVisibility(View.VISIBLE);
            rlThird.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_cancel) {
            dismiss();
        }
    }

}
